import os
from fastapi import APIRouter,Path,Query,Cookie,Header,status
from typing import Optional,List,Union,Any
from pydantic import BaseModel,Field,EmailStr

app03 = APIRouter()

@app03.get("/")
async def index():
    return {
        "name":os.path.basename(__file__)
    }


class UserReg(BaseModel):
    username:str
    password:str
    address:str
    mobile:str = 15099999999
    email:EmailStr

class UserOut(BaseModel):
    username: str
    address: str
    mobile: str = 15099999999
    email: EmailStr = None
    reg_state: int = 0    #表示注册状态

users = [
    {"username":"马哈哈","password":"12355","address":"隆兴大厦2#","mobile":"15098765432","email":"xxxx@163.com"},
    {"username":"引申思","password":"98765","address":"隆兴大厦2#"},
    {"username":"露露","address":"隆兴大厦2#","mobile":"15399994444","reg_state":2},
]

@app03.post("/user/reg",response_model=UserOut,response_model_exclude_unset=True)
async def reg_user(user:UserReg):
    """
    不仅由请求模型，也有响应模型，可以在路由装饰器里指定 response_model
    response_model_exclude_unset 为True时，不会将默认值返回，比如例子中不会返回 mobile: 15099999999
    """
    print(user.json())
    return users[1]



@app03.post("/user/reg2",response_model=Union[UserOut,UserReg])
async def reg_user2(user:UserReg):
    """
    通过Union来设置响应模型可以为2者中的任意一种,
    而且会将请求模型中的对应值赋给响应模型
    """
    return user

@app03.get("/user/{id}",response_model=Union[UserReg,UserOut])
async def reg_user2(id:int):
    """
    通过Union来设置响应模型可以为2者中的任意一种
    """
    return users[id]

@app03.get("/status",status_code=200)
async def get_status():
    return {
        "status_code":200
    }
@app03.get("/status2",status_code=status.HTTP_200_OK)
async def get_status():
    return {
        "status_code":status.HTTP_200_OK
    }